////////////////////////////////////////////////////////////////////////////////
//  Copyright 2011 Adam Kidd
//  
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  
//    http://www.apache.org/licenses/LICENSE-2.0
//  
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
////////////////////////////////////////////////////////////////////////////////

package com.arcadefoundry.rest.http.client
{
	import com.arcadefoundry.rest.http.IHTTPRequest;
	import com.arcadefoundry.rest.http.events.HTTPSocketEvent;
	
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;

	public class HTTPClient extends EventDispatcher
	{
		//------------------------------------------------
		//
		// Properties
		//
		//------------------------------------------------
		/**
		 * Determines if the server is currently sending a request. 
		 */
		private var isBusy:Boolean;
		
		/**
		 * The socket through which communication will take place. 
		 */
		private var socket:HTTPSocket;
		
		//------------------------------------------------
		//
		// Constructor
		//
		//------------------------------------------------
		/**
		 * The <code>HTTPClient</code> is for communicating with REST-based web
		 * services. Currently only GET, PUT, POST and DELETE verbs are 
		 * supported.
		 * 
		 * @param host The root URI of the targeted HTTP server.
		 * @param port The port of the targeted HTTP server.
		 * 
		 */
		public function HTTPClient(host:String, port:int = 80)
		{
			this.socket = new HTTPSocket(host, port);
			this.socket.addEventListener(HTTPSocketEvent.DATA_RECEIVED, onDataReceived);
		}
		
		//------------------------------------------------
		//
		// Methods
		//
		//------------------------------------------------
		/**
		 * Sends an HTTP request.
		 *  
		 * @param request The request to be sent.
		 * 
		 */
		public function send(request:IHTTPRequest):void
		{
			// Prevent sending multiple requests simultaneously.
			if (!this.isBusy)
			{
				this.isBusy = true;
				socket.send(request);
			}
			else
			{
				throw new Error("The client is already sending a request.");
			}
		}
		
		// Temporary dispatcher to display received data in the test app.
		private function onDataReceived(event:HTTPSocketEvent):void
		{
			dispatchEvent(event);
		}
	}
}
